﻿
Imports osi.root.constants
Imports osi.root.delegates
Imports osi.root.connector
Imports osi.root.envs

Public Module _assert
    Sub New()
        If assert_trace Then
            setstrongassert()
        End If
    End Sub

    Private Sub assert_raise_error(ByVal assertlevel As String,
                                   ByVal msgs() As Object)
        raise_error(error_type.critical,
                    assertlevel,
                    If(isemptyarray(msgs), " failed.", " failed, "),
                    msgs,
                    newline.incode(),
                    callstack())
    End Sub

    Private Function assert_failed(ByVal msgs() As Object) As Boolean
        assert_raise_error("assert", msgs)
        Return k_assert(False, msgs)
    End Function

    Private Function debug_assert_failed(ByVal msgs() As Object) As Boolean
        assert_raise_error("debug assert", msgs)
        Return Not isdebugmode() AndAlso k_assert(False, msgs)
    End Function

    Public Function debugassert(ByVal v As Boolean) As Boolean
        Return v OrElse debug_assert_failed(Nothing)
    End Function

    Public Function debugassert(ByVal v As Boolean, ByVal ParamArray msgs() As Object) As Boolean
        Return v OrElse debug_assert_failed(msgs)
    End Function

    Public Function assert(ByVal v As Boolean) As Boolean
        Return v OrElse assert_failed(Nothing)
    End Function

    Public Function assert(ByVal v As Boolean, ByVal ParamArray msgs() As Object) As Boolean
        Return v OrElse assert_failed(msgs)
    End Function

    Public Function assert_return(Of T)(ByVal v As Boolean, ByVal i As T, ByVal ParamArray msgs() As Object) As T
        assert(v, msgs)
        Return i
    End Function

    Public Function assert_return(Of T)(ByVal v As _do(Of Boolean),
                                        ByVal i As T,
                                        ByVal ParamArray msgs() As Object) As _do(Of T)
        Return assert_do(v,
                         Function() As T
                             Return i
                         End Function,
                         msgs)
    End Function

    Public Function assert_do(Of T)(ByVal v As _do(Of Boolean),
                                    ByVal i As _do(Of T),
                                    ByVal ParamArray msgs() As Object) As _do(Of T)
        Return Function() As T
                   assert(do_(v, False), msgs)
                   Return do_(i, Nothing)
               End Function
    End Function
End Module
